package com.im.service.jim.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.im.service.domain.entity.ImChat;
import com.im.service.domain.entity.ImUser;
import com.im.service.jim.ChatSessionUtil;
import com.im.service.service.ImChatService;
import com.im.service.service.ImUserService;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.packets.User;
import org.jim.core.packets.UserStatusType;
import org.jim.server.JimServerAPI;
import org.jim.server.listener.AbstractImUserListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author WChao
 * @Desc
 * @date 2020-05-02 18:18
 */
@Component
public class ImUserListener extends AbstractImUserListener {

    private static Logger logger = LoggerFactory.getLogger(ImUserListener.class);

    @Autowired
    private ImUserService imUserService;

    @Autowired
    private ImChatService chatService;

    @Override
    public void doAfterBind(ImChannelContext imChannelContext, User user) {
        ImUser imUser = imUserService.getById(user.getUserId());
        imUser.setStatus(UserStatusType.ONLINE.getStatus());
        imUserService.updateById(imUser);
        logger.info("绑定用户:{}", JSONObject.toJSONString(user));
        offlineOrOnline(user, imUser);
        ChatSessionUtil.sendNewSessionToImChannelContext(imChannelContext, user.getUserId());
    }

    @Override
    public void doAfterUnbind(ImChannelContext imChannelContext, User user) {
        List<ImChannelContext> list = JimServerAPI.getByUserId(user.getUserId());
        if (CollectionUtil.isEmpty(list) ||
                list.size() == 1 &&
                        StrUtil.equals(list.get(0).getId(), imChannelContext.getId())
        ) {
            ImUser imUser = imUserService.getById(user.getUserId());
            imUser.setStatus(UserStatusType.OFFLINE.getStatus());
            imUserService.updateById(imUser);
            // 通知会话离线
            offlineOrOnline(user, imUser);
        }
        imChannelContext.remove("chatId");
        ChatSessionUtil.sendNewSessionToUser(user.getUserId());
        logger.info("解绑用户:{}", JSONObject.toJSONString(user));
    }

    private void offlineOrOnline(User user, ImUser imUser) {
        List<ImChat> chatList = chatService.list(
                Wrappers.lambdaQuery(ImChat.class)
                        .eq(ImChat::getTargetId, user.getUserId())
        );
        for (ImChat imChat : chatList) {
            ImPacket imPacket = new ImPacket();
            imPacket.setStatus(ImStatus.C10000);
            imPacket.setCommand(Command.CHAT_OFFLINE_ONLINE);
            imPacket.setBody(new RespBody(Command.CHAT_OFFLINE_ONLINE, imUser).toByte());
            JimServerAPI.sendToUser(String.valueOf(imChat.getUserId()), imPacket);
        }
    }
}
